package com.zzy.netty.learn.demo.client;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
 * 
* Title: NettyClientFilter
* Description: Netty客户端 过滤器
* Version:1.0.0  
* @author guokaige
* @date 2017-8-31
 */
public class NettyClientFilter extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
    	
    	
        ChannelPipeline pipeline = ch.pipeline();
      
		// 负责通过4字节Header指定的Body长度将消息切割
		pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		// 负责将写入的字节码加上4字节Header前缀来指定Body长度
		pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
		// 解码和编码，应和客户端一致
		pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
		pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
		
		
		pipeline.addLast("handler", new NettyClientHandler()); //客户端的逻辑
    }
}